/*
 * Copyright (C) 2011 TargetBoard
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package contrl;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import contrl.model.Model;
import contrl.model.ModelFactory;

import jaxb.InitailizedException;
import jaxb.XmlManager;



/**
 * Servlet implementation class BoardController
 * @author amc
 *
 */
public class BoardController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BoardController() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("edit");
		RequestDispatcher rd;
		if (type!=null && type.equals("users")) {
			rd = request.getRequestDispatcher("WEB-INF/jsp/EditBoard.jsp");
		} else if (type!=null && type.equals("data")) {
			rd = request.getRequestDispatcher("WEB-INF/jsp/EditBoard.jsp");
		} else if (type!=null && type.equals("reload data")) {
			XmlManager.getInstance().resetData();
			rd = request.getRequestDispatcher("WEB-INF/jsp/Board.jsp");
		} else {
			rd = request.getRequestDispatcher("WEB-INF/jsp/Board.jsp");
		}
		try {
			Cookie cookie = findUserCookie(request.getCookies());
			if (cookie != null) {
				request.setAttribute("USER", cookie.getValue());
			}
			Model dataModel = ModelFactory.getXmlModel();
			request.setAttribute("table", dataModel.getModelTable());
			request.setAttribute("users", dataModel.getUsersList());
			request.setAttribute("desc", dataModel.getDescription());
			request.setAttribute("history", dataModel.generateHistory());
			// request.setAttribute("uimap", dataModel.getUiMap());
			// request.setAttribute("collapse", dataModel.getCollapse());
		} catch (InitailizedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] keys = request.getParameterValues("group");
		String user = request.getParameter("user");
		String button = request.getParameter("button");
		if (user != null && keys != null) {
			try {
				if ((button != null && button.equals("Unreserve")) || user.length() == 0) {
					user = null;
				} else {
					updateUserCookie(request, response);
				}
				if (keys.length > 0) {
					XmlManager.getInstance().setBook(user, keys);
				}
			} catch (InitailizedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		response.sendRedirect("Board");
	}

	private void updateUserCookie(HttpServletRequest request, HttpServletResponse response) {
		String user = request.getParameter("user");
		if (user != null) {
			Cookie userCookie = findUserCookie(request.getCookies());
			Cookie cookie = new Cookie("USER", user);
			cookie.setMaxAge(365 * 24 * 60 * 60);
			if (userCookie != null) {
				if (!userCookie.getValue().equals(user)) {
					response.addCookie(cookie);
				}
			} else {
				response.addCookie(cookie);
			}
		}
	}

	private Cookie findUserCookie(Cookie[] cookies) {
		Cookie userCookie = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("USER")) {
					userCookie = cookie;
					break;
				}
			}
		}
		return userCookie;
	}
}
